//
//  OverlayPresentationController.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/6.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "OverlayPresentationController.h"

@interface OverlayPresentationController ()
@property (strong, nonatomic) UIView *dimmingView;
@end

@implementation OverlayPresentationController

- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController
{
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
    if (self) {
        self.dimmingView = [[UIView alloc] init];
        self.dimmingView.backgroundColor = [UIColor blackColor];
        self.dimmingView.alpha = 0.f;
    }
    return self;
}

- (void)presentationTransitionWillBegin {
    [self.containerView addSubview:self.dimmingView];
    
    self.dimmingView.center = self.containerView.center;
    self.dimmingView.bounds = CGRectMake(0, 0, CGRectGetWidth(self.containerView.frame) * 2 / 3.f, CGRectGetHeight(self.containerView.frame) * 2 / 3.f);
    self.dimmingView.alpha = .5f;
    
    [self.presentingViewController.transitionCoordinator
     animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
         self.dimmingView.bounds = self.containerView.bounds;
    } completion:nil];
}

- (void)presentationTransitionDidEnd:(BOOL)completed {
    if (!completed) {
        [self.dimmingView removeFromSuperview];
    }
}

- (void)dismissalTransitionWillBegin {
    [self.presentedViewController.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        self.dimmingView.alpha = 0.f;
    } completion:nil];
}

- (void)dismissalTransitionDidEnd:(BOOL)completed {
    if (completed) {
        [self.dimmingView removeFromSuperview];
    }
}

- (CGRect)frameOfPresentedViewInContainerView {
    CGFloat width = CGRectGetWidth(self.containerView.frame) * 2 / 3.f;
    CGFloat height = CGRectGetHeight(self.containerView.frame) * 2 / 3.f;
    CGFloat x = (CGRectGetWidth(self.containerView.frame) - width) / 2.f;
    CGFloat y = (CGRectGetHeight(self.containerView.frame) - height) / 2.f;
    
    return CGRectMake(x, y, width, height);
}

- (UIView *)presentedView {
    self.presentedViewController.view.layer.cornerRadius = 8.f;
    self.presentedViewController.view.layer.masksToBounds = YES;
    
    return self.presentedViewController.view;
}

- (void)containerViewWillLayoutSubviews {
    self.dimmingView.center = self.containerView.center;
    self.dimmingView.bounds = self.containerView.bounds;
    
    self.presentedView.center = self.containerView.center;
    self.presentedView.bounds = (CGRect){CGPointZero, CGSizeMake(CGRectGetWidth(self.containerView.frame) * 2 / 3.f, CGRectGetHeight(self.containerView.frame) * 2 / 3.f)};
}

@end
